package com.hlj.smartpad.launcher

import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.core.content.ContextCompat.startActivity
import com.google.gson.Gson
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel


class ChannelUtils(flutterEngine: BinaryMessenger, context: Context) :
    MethodChannel.MethodCallHandler {

    private val batteryChannelName = "com.hlj.smartpad.android/launcher"

    private var channel: MethodChannel
    private var mContext: Context

    companion object {
        private const val TAG = "ChannelUtils"
    }

    init {
        Log.d(TAG, "init")
        channel = MethodChannel(flutterEngine, batteryChannelName)
        channel.setMethodCallHandler(this)
        mContext = context;
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        Log.d(TAG, "onMethodCall: " + call.method)
        when (call.method) {
            "evoke_app" -> {
                val appPackage = arrayOf(call.arguments.toString())
                AppUtils.reStartApp(mContext, appPackage)
                result.success("success")
            }
            "jump_page" -> {
                val pkgName = call.arguments.toString()
                val intent = Intent(pkgName)
                mContext.startActivity(intent)
                result.success("success")
            }
            "get_status" -> {
                Log.d(TAG, "get_status: " + MainActivity.restatus)
                result.success(MainActivity.restatus)
            }
            "set_status" -> {
                Log.d(TAG, "set_status: " + call.arguments)
                MainActivity.restatus = call.arguments as Boolean
                result.success("success")
            }
            "app_info" -> {
                val listStr = call.arguments as ArrayList<String>;
                val resultList = AppUtils.getAppInfo(mContext, listStr)
                val jsonStr = Gson().toJson(resultList)
                result.success(jsonStr)
            }
        }
    }
}
